using System.Collections.Generic;
using UnityEngine;

namespace FrameWork
{
    public class UIHelper : MonoBehaviour, IUIHelper
    {
        [SerializeField]
        private Transform _uiRoot;

        [SerializeField]
        private GameObject _template;

        /// <summary>
        /// 界面池父物体
        /// </summary>
        [SerializeField]
        private Transform _poolTrans;

        [SerializeField]
        private int _defaultInterval;

        private Dictionary<UILayer, Transform> _layers;

        /// <summary>
        /// 界面回收时间
        /// </summary>
        public int RecycleInterval => _defaultInterval;

        private void Start()
        {
            _layers = new Dictionary<UILayer, Transform>();
            UIModule uiModule = ModuleGetter.UIModule;
            uiModule.RegisterHelper(this);
        }

        /// <summary>
        /// 处理界面创建
        /// </summary>
        public UILogic ExecuteUIDialog(GameObject dialogGo, ViewInfo viewInfo)
        {
            var parent = GetUIParent(viewInfo.UILayer);
            if (parent != null)
            {
                dialogGo.transform.SetParent(parent, false);
            }

            var uiLogic = dialogGo.GetOrAddComponent<UILogic>();
            uiLogic.OnInit();
            return uiLogic;
        }

        /// <summary>
        /// 获取UI父物体
        /// </summary>
        private Transform GetUIParent(UILayer uilayer)
        {
            if (_layers.TryGetValue(uilayer, out var tran))
            {
                return tran;
            }

            return CreateUIParent(uilayer);
        }

        /// <summary>
        /// 创建UI父物体
        /// </summary>
        private Transform CreateUIParent(UILayer uiLayer)
        {
            if (_layers.ContainsKey(uiLayer))
            {
                Debug.LogError("该layer已经存在!!!");
                return null;
            }

            GameObject parent = GameObject.Instantiate(_template);
            parent.SetActive(true);
            parent.transform.SetParent(_uiRoot, false);
            parent.name = uiLayer.ToString();
            _layers[uiLayer] = parent.transform;
            return parent.transform;
        }

        public void AddUIToSleep(Transform trans)
        {
            trans.SetParent(_poolTrans, false);
        }
    }
}
